package com.mangguo.tingjian.account.rest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.common.ResultStatus;
import com.mangguo.tingjian.account.dto.UserDto;
import com.mangguo.tingjian.account.dto.UserQueryReq;
import com.mangguo.tingjian.account.entity.User;
import com.mangguo.tingjian.account.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserRestController {

   private final UserService userService;

   public UserRestController(UserService userService) {
      this.userService = userService;
   }

   @GetMapping("/get")
   public Result<User> getActualUser() {
      return Result.success(userService.getUserWithAuthorities().get());
   }

   @PostMapping("/create")
   public Result<Boolean> createUser(@Valid @RequestBody UserDto userDto){
      log.info("create user userDto:{}", JSONObject.toJSONString(userDto));
      return Result.success(userService.createUser(userDto));
   }

   @PostMapping("/update")
   public Result<Boolean> updateUser(@Valid @RequestBody UserDto userDto){
      log.info("update user userDto:{}", JSONObject.toJSONString(userDto));
      return Result.success(userService.updateUser(userDto));
   }

   /**
    * 更新用户有效状态
    * @param userDto
    * @return
    */
   @PostMapping("/valid")
   public Result<Boolean> validUser(@RequestBody UserDto userDto){
      if(userDto.getId() == null || userDto.getIsValid() == null){
         return Result.error(ResultStatus.PARAMETER_ISNULL);
      }
      log.info("valid user id:{} valid:{}", userDto.getId(), userDto.getIsValid());
      return Result.success(userService.validUser(userDto.getId(), userDto.getIsValid()));
   }

   /**
    * 删除用户
    * @param userDto
    * @return
    */
   @PostMapping("/delete")
   public Result<Boolean> deleteUser(@RequestBody UserDto userDto){
      if(userDto.getId() == null){
         return Result.error(ResultStatus.PARAMETER_ISNULL);
      }
      log.info("delete user userDto:{}", userDto.getId());
      return Result.success(userService.deleteUser(userDto.getId()));
   }

   /**
    * 分页查询
    * @param req
    * @return
    */
   @GetMapping("/page")
   public Result<IPage<User>> selectPageUser(@Valid UserQueryReq req){
      return Result.success(userService.selecPage(req));
   }

   /**
    * 更新密码
    * @param userDto
    * @return
    */
   @PostMapping("/update-password")
   public Result<Boolean> updatePassword(@RequestBody UserDto userDto){
      if(userDto.getId() == null || userDto.getPassword() == null){
         return Result.error(ResultStatus.PARAMETER_ISNULL);
      }
      log.info("user update password, id:{}", userDto.getId());
      return Result.success(userService.updatePassWord(userDto.getId(), userDto.getPassword()));
   }
}
